package ren.install.web.controller;

import cn.hutool.core.io.IoUtil;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import ren.install.web.config.ValueCenter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhuyh
 * @date: 2018/11/21
 */
@Controller
@RequestMapping("static")
@Slf4j
public class StaticController {

    @Autowired
    private ValueCenter valueCenter;

    @GetMapping("image/{date}/{file}")
    public void image(HttpServletRequest request, HttpServletResponse response,
                      @PathVariable("date") String date, @PathVariable("file") String file) throws Exception {
        log.info("request image is:{}" + request.getServletPath());
        long start = System.currentTimeMillis();
        response.setContentType("image/" + file.substring(file.lastIndexOf(".") + 1));
        //Expires:过时期限值
        response.setDateHeader("Expires", System.currentTimeMillis() + 6000000);
        response.setHeader("Cache-Control", "public");
        response.setHeader("Pragma", "Pragma");

        String image = valueCenter.getStaticFilePath()
                + File.separator
                + "image"
                + File.separator
                + date
                + File.separator
                + file;

        @Cleanup
        InputStream inputStream = new FileInputStream(image);

        byte[] bytes = IoUtil.readBytes(inputStream);
        response.getOutputStream().write(bytes);

        log.info("cost:{}ms", System.currentTimeMillis() - start);

    }

    @GetMapping("html/{file}")
    public void html(HttpServletRequest request, HttpServletResponse response,
                       @PathVariable("file") String file) throws Exception {
        log.info("request html is:{}" + request.getServletPath());
        long start = System.currentTimeMillis();
        response.setContentType("text/html");
        String html = valueCenter.getStaticFilePath()
                + File.separator
                + "html"
                + File.separator
                + file;

        @Cleanup
        InputStream inputStream = new FileInputStream(html);

        byte[] bytes = IoUtil.readBytes(inputStream);
        response.getOutputStream().write(bytes);

        log.info("cost:{}ms", System.currentTimeMillis() - start);

    }
}
